package com.xz.hlx11;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class UserData {
    private static final String TAG = "UserData";
    private static final String USER_DATA_FILE = "user_login.json";
    
    private Context context;
    private String userId = "";
    private String userKey = "";
    private String username = "";

    public UserData(Context context) {
        this.context = context;
        loadUserData();
    }

    public void saveUserData(String userId, String userKey, String username) {
        Log.d(TAG, "开始保存用户数据 - 用户名: " + username + ", 用户ID: " + userId + ", Key长度: " + userKey.length());
        
        this.userId = userId;
        this.userKey = userKey;
        this.username = username;
        
        // 创建JSON对象保存数据
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("user_id", userId);
        jsonObject.addProperty("user_key", userKey);
        jsonObject.addProperty("username", username);
        jsonObject.addProperty("save_time", System.currentTimeMillis());
        
        String jsonString = jsonObject.toString();
        Log.d(TAG, "准备保存的JSON内容: " + jsonString);
        
        // 保存到文件
        try {
            File dataDir = context.getFilesDir();
            File userFile = new File(dataDir, USER_DATA_FILE);
            
            Log.d(TAG, "保存到文件路径: " + userFile.getAbsolutePath());
            
            FileOutputStream fos = new FileOutputStream(userFile);
            fos.write(jsonString.getBytes("UTF-8"));
            fos.close();
            
            Log.d(TAG, "用户数据保存成功，文件大小: " + userFile.length() + " bytes");
        } catch (IOException e) {
            Log.e(TAG, "保存用户数据失败", e);
        }
    }

    private void loadUserData() {
        try {
            File dataDir = context.getFilesDir();
            File userFile = new File(dataDir, USER_DATA_FILE);
            
            Log.d(TAG, "尝试加载用户数据，文件路径: " + userFile.getAbsolutePath());
            
            if (!userFile.exists()) {
                Log.d(TAG, "用户数据文件不存在");
                return;
            }
            
            Log.d(TAG, "文件存在，大小: " + userFile.length() + " bytes");
            
            FileInputStream fis = new FileInputStream(userFile);
            byte[] buffer = new byte[(int) userFile.length()];
            fis.read(buffer);
            fis.close();
            
            String jsonString = new String(buffer, "UTF-8");
            Log.d(TAG, "读取到的JSON内容: " + jsonString);
            
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
            
            if (jsonObject != null) {
                this.userId = jsonObject.has("user_id") ? jsonObject.get("user_id").getAsString() : "";
                this.userKey = jsonObject.has("user_key") ? jsonObject.get("user_key").getAsString() : "";
                this.username = jsonObject.has("username") ? jsonObject.get("username").getAsString() : "";
                
                Log.d(TAG, "用户数据加载成功 - 用户名: " + username + ", 用户ID: " + userId + ", Key长度: " + userKey.length());
            } else {
                Log.e(TAG, "JSON解析失败，jsonObject为null");
            }
        } catch (Exception e) {
            Log.e(TAG, "加载用户数据失败", e);
            // 清空数据以防止错误
            this.userId = "";
            this.userKey = "";
            this.username = "";
        }
    }

    public String getUserId() {
        return userId;
    }

    public String getUserKey() {
        return userKey;
    }

    public String getUsername() {
        return username;
    }

    public boolean hasUserData() {
        return !getUserId().isEmpty() && !getUserKey().isEmpty();
    }

    public void clearUserData() {
        // 清空内存中的数据
        this.userId = "";
        this.userKey = "";
        this.username = "";
        
        // 删除文件
        try {
            File dataDir = context.getFilesDir();
            File userFile = new File(dataDir, USER_DATA_FILE);
            
            if (userFile.exists()) {
                boolean deleted = userFile.delete();
                Log.d(TAG, "用户数据文件删除" + (deleted ? "成功" : "失败"));
            }
        } catch (Exception e) {
            Log.e(TAG, "删除用户数据文件失败", e);
        }
    }
    
    public String getUserDataFilePath() {
        File dataDir = context.getFilesDir();
        File userFile = new File(dataDir, USER_DATA_FILE);
        return userFile.getAbsolutePath();
    }
    
    public boolean userDataFileExists() {
        File dataDir = context.getFilesDir();
        File userFile = new File(dataDir, USER_DATA_FILE);
        return userFile.exists();
    }
    
    public long getSaveTime() {
        try {
            File dataDir = context.getFilesDir();
            File userFile = new File(dataDir, USER_DATA_FILE);
            
            if (!userFile.exists()) {
                return 0;
            }
            
            FileInputStream fis = new FileInputStream(userFile);
            byte[] buffer = new byte[(int) userFile.length()];
            fis.read(buffer);
            fis.close();
            
            String jsonString = new String(buffer, "UTF-8");
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
            
            if (jsonObject != null && jsonObject.has("save_time")) {
                return jsonObject.get("save_time").getAsLong();
            }
            
            return 0;
        } catch (Exception e) {
            Log.e(TAG, "获取保存时间失败", e);
            return 0;
        }
    }
    
    // 检查登录信息是否过期（30天）
    public boolean isLoginExpired() {
        long saveTime = getSaveTime();
        if (saveTime == 0) {
            return true;
        }
        
        long currentTime = System.currentTimeMillis();
        long daysDiff = (currentTime - saveTime) / (1000 * 60 * 60 * 24);
        
        Log.d(TAG, "登录信息保存时间差: " + daysDiff + " 天");
        
        // 如果超过30天，认为过期
        return daysDiff > 30;
    }
}
